//
//  CustomViewController.m
//  UIPickerViewDemo
//
//  Created by student on 16/2/24.
//  Copyright © 2016年 NIIT. All rights reserved.
//

#import "CustomViewController.h"
#import <AudioToolbox/AudioToolbox.h>


@interface CustomViewController ()<UIPickerViewDataSource,UIPickerViewDelegate>
{
    SystemSoundID winSoundID;
    SystemSoundID normalSoundID;
}

@property (nonatomic,strong) NSArray *images;

@end

@implementation CustomViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.images = @[[UIImage imageNamed:@"apple"],
                    [UIImage imageNamed:@"bar"],
                    [UIImage imageNamed:@"cherry"],
                    [UIImage imageNamed:@"crown"],
                    [UIImage imageNamed:@"lemon"],
                    [UIImage imageNamed:@"seven"]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)btnPressed:(id)sender
{
    BOOL win = NO;
    for (int i=0; i<5; i++)
    {
        int sel = arc4random()%6;
        [self.pickerView selectRow:sel inComponent:i animated:YES];
    }
    if (win)
    {
        [self playWinSound];
    }
    else
    {
        [self playNormalSound];
    }
}

- (void)playWinSound
{
    if (winSoundID == 0)
    {
        //声音文件的位置
        NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"win" withExtension:@"wav"];
        //注册短声音
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(soundURL), &winSoundID);
    }
    AudioServicesPlayAlertSound(winSoundID);
}

- (void)playNormalSound
{
    if (normalSoundID == 0)
    {
        //声音文件的位置
        NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"win" withExtension:@"wav"];
        //注册短声音
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(soundURL), &normalSoundID);
    }
    AudioServicesPlayAlertSound(normalSoundID);
}


- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return  5;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 6;
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(nullable UIView *)view
{
    UIImageView *imageView = [[UIImageView alloc] initWithImage:self.images[row]];
    return imageView;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 52;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 46;
}


@end
